package response

import (
	"net/http"

	"gitee.com/liuxiaowei123/vblog-01/vblog-01/vblog/exception"
	"github.com/gin-gonic/gin"
)

// 正常情况下的响应
func Success(c *gin.Context, data any) {
	c.JSON(http.StatusOK, data)
}

// 异常情况下的数据响应
func Failed(c *gin.Context, err error) {
	// 确保HTTP请求在函数执行完毕或提前退出时被正确地中止。这样可以避免不必要的延迟或资源消耗
	defer c.Abort()
	var e *exception.ApiException
	if v, ok := err.(*exception.ApiException); ok {
		e = v
	} else {
		// 非可以预期, 没有定义业务码的情况，BizCode和HttpCode都为500
		e = exception.NewApiException(http.StatusInternalServerError, err.Error())
		e.HttpCode = http.StatusInternalServerError
	}
	c.JSON(e.HttpCode, e)

}
